/* 
 * Copyright 2011 Carnegie Mellon University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package edu.cmu.lti.dimple;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

import edu.cmu.lti.dimple.data.Pair;

/**
 * A class that is responsible for filtering out 
 * pairs with respect to a specific criterion. 
 * 
 * @author Hideki Shima
 *
 * @param <T>
 */
public class PairFilter<T extends Pair> {

  public List<T> filterByWord( List<T> pairs, 
          String grepKeyWord ) {
    List<T> newPairs = new ArrayList<T>(pairs.size());
    for ( T p : pairs ) {
      Pattern pattern = Pattern.compile("\\b"+grepKeyWord+"\\b");
      if (pattern.matcher(p.getText1()).find() || pattern.matcher(p.getText2()).find()) {
        newPairs.add(p);
      }
    }
    return newPairs;
  }

  public List<T> filterByLabel( List<T> pairs, String label ) {
    List<T> newPairs = new ArrayList<T>(pairs.size());
    for ( T p : pairs ) {
      if ( p.getLabel().equals(label) ) {
        newPairs.add(p);
      }
    }
    return newPairs;
  }
  
  // One and only one of two texts must have keyword, but not both two. 
  public List<T> filterByXOR( List<T> pairs, 
          String grepKeyWord ) {
    List<T> newPairs = new ArrayList<T>(pairs.size());
    for ( T p : pairs ) {
      Pattern pattern = Pattern.compile("\\b"+grepKeyWord+"\\b");
      boolean found1 = pattern.matcher(p.getText1()).find();
      boolean found2 = pattern.matcher(p.getText2()).find();      
      if ( (found1&&!found2) || (!found1&&found2) ) {
        newPairs.add(p);
      }
    }
    return newPairs;
  }
  
  public void removeDuplicated( List<T> pairs ) {
    List<T> toBeRemoved = new ArrayList<T>(pairs.size());
    Set<String> history = new HashSet<String>();
    for ( T t : pairs ) {
      String key = t.getText1()+"<>"+t.getText2();
      if (history.contains(key)) {
        toBeRemoved.add(t);
      } else {
        history.add(key);
      }
    }
    pairs.removeAll(toBeRemoved);
  }

  public static boolean intersect(Set<String> history, List<String> words) {
    for ( String word : words ) {
      if ( history.contains(word) ) return true;
    }
    return false;
  }
  
}
